﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Runtime.Gateway;
using Phoenix.ZeroMQConnectors;
using PServiceBus.Gateway.Interfaces;
using PServiceBus.Gateway.ZeroMQ.DTO;
using PServiceBus.Gateway.ZeroMQ.Commands;
using PServiceBus.Gateway.Interfaces.DTO;
using PServiceBus.Gateway.Interfaces.Commands;

namespace PServiceBus.Gateway.ZeroMQ {
    public sealed class ZeroMQBusRouter : IBusRouter {

        private ZeroMQSender _client;

        public ZeroMQBusRouter() { }

        public ZeroMQBusRouter(string address) {
            _client = new ZeroMQSender(ZeroMQEndpointUri.Parse(address));
        }

        #region IBusRouter Members

        public ServiceInfo[] GetServices() {
            return _client.Send<ZeroMQRouterRequest,ZeroMQServiceInfos>(ZeroMQRouterRequest.Empty).Services;
        }

        public void SetConnectedClients(Guid id, bool decrement) {
            _client.Send<RouterMessage>(ZeroMQRouterMessage.New(id: id, decrement: decrement, async: false));
        }

        public void DeleteService(Guid id) {
            _client.Send<RouterMessage>(ZeroMQRouterMessage.New(id: id, async: false));
        }

        public IBusRouter Init(string address) {
            return new ZeroMQBusRouter(address);
        }

        #endregion

        #region IDisposable Members

        public void Dispose() {
            try {
                if (_client != null) _client.Dispose();
                _client = null;
            } catch { }
        }

        #endregion
    }
}
